package com.haiyang.gateway.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.interfaces.RSAPublicKey;

/**
 * @BelongsProject: ms
 * @BelongsPackage: com.haiyang.gateway.config
 * @Author: BHY
 * @CreateTime: 2023-10-31  14:05
 * @Description: TODO
 * @Version: 1.0
 */
@Component
@Slf4j
public class GloablFilter implements GlobalFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("Authorization");
        try {
            String publicKeyStr = redisTemplate.opsForValue().get("PUB_CACHE");
            RSAPublicKey publicKey = JwtUtils.getPublicKey(publicKeyStr);
            Claims body = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token.replace("Bearer ", "")).getBody();
            log.info("当前用户:{},请求地址:{}",body.get("sub"),request.getPath());
            return chain.filter(exchange);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
